package com.h1909d.weinfo.receiver;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.util.Log;

import com.h1909d.weinfo.R;
import com.h1909d.weinfo.ui.activity.NaviActivity;
import com.h1909d.weinfo.ui.activity.NewsDetailActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Iterator;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.helper.Logger;

public class CustomReceiver extends BroadcastReceiver {
    private NotificationManager nm;

    @Override
    public void onReceive(Context context, Intent intent) {

        if (null == nm) {
            nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        }

        Bundle bundle = intent.getExtras();
        Logger.d("TAG", "onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));

        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
            Logger.d("TAG", "JPush 用户注册成功");

        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
            Logger.d("TAG", "接受到推送下来的自定义消息");
            sendNotification(context,bundle.getString(JPushInterface.EXTRA_MESSAGE));

        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
            Logger.d("TAG", "接受到推送下来的通知");


        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
            Logger.d("TAG", "用户点击打开了通知");


        } else {
            Logger.d("TAG", "Unhandled intent - " + intent.getAction());
        }
    }

    private void sendNotification(Context context, String msg) {
        //{"type":"2","msg":"来看美女啊","id":"48943924"}
        //type:1,跳转到新闻详情页面
        //type:2,跳转到导航页面
        //解析数据
        try {
            JSONObject jsonObject = new JSONObject(msg);
            String type = jsonObject.optString("type");
            String title = jsonObject.optString("msg");
            String newsId = jsonObject.optString("id");


            //发送通知
            //1.获取通知管理器
            //2.创建notificationChannel,适配8.0以上系统
            String id = "weinfo";
            CharSequence name = "jpush";
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                NotificationChannel channel = new NotificationChannel(id,name,NotificationManager.IMPORTANCE_DEFAULT);
                nm.createNotificationChannel(channel);
            }
            //3.构建Notification对象

            Intent intent;
            if (type.equals("1")){
                intent = new Intent(context, NewsDetailActivity.class);
                intent.putExtra("newsId",Integer.parseInt(newsId));
            }else {
                intent = new Intent(context, NaviActivity.class);
            }
            PendingIntent pendingIntent = PendingIntent.getActivity(context,100,intent,PendingIntent.FLAG_CANCEL_CURRENT);

            Notification notification = new NotificationCompat.Builder(context,id)
                    .setContentTitle(title)
                    .setSmallIcon(R.drawable.add)
                    .setContentText(title + ":" + id + "," + type)
                    .setContentIntent(pendingIntent)
                    .setAutoCancel(true)
                    .build();
            //4.发送通知
            nm.notify(1,notification);
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    // 打印所有的 intent extra 数据
    private static String printBundle(Bundle bundle) {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
            } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
            } else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
                if (TextUtils.isEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA))) {
                    Log.i("TAG", "This message has no Extra data");
                    continue;
                }

                try {
                    JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                    Iterator<String> it = json.keys();
                    while (it.hasNext()) {
                        String myKey = it.next().toString();
                        sb.append("\nkey:" + key + ", value: [" +
                                myKey + " - " + json.optString(myKey) + "]");
                    }
                } catch (JSONException e) {
                    Log.e("TAG", "Get message extra JSON error!");
                }

            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
            }
        }
        return sb.toString();
    }
}
